package reservice;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;


import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;


import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

import controller.Domain;
import controller.ReDomain;


public class GooglePageRank extends Thread{
	ReDomain domain;
	public GooglePageRank(ReDomain domain)
	{
		System.out.println(domain);
		this.domain=domain;
		this.start();
	}
	public void run()
	{
		String message = null;
		try {
			message = URLEncoder.encode(domain.getName(), "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}


        try {
        	
        	URL url = new URL("http://get-pagerank.appspot.com/pagerank?name=http://"+message);
        	HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setReadTimeout(500000);
    		connection.setConnectTimeout(1000000);
    		BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("iso-8859-1")));
    		String content = "";
	       	 while(1==1)
				 {
					 String str = reader.readLine();
					 if(str==null) break;
					 content+=str;   				
				 }
	       	
	       	 String googlePageRank = "0";
	       	 if(content != null && !content.equals(""))
	       	 {
	       		 googlePageRank = content;
	       	 }

			 domain.setGoogle(googlePageRank);
	
        } catch (MalformedURLException e) {
            // ...
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
	public static void main( String args[])
	{
		ReDomain domain = new ReDomain();
		domain.setName("abc.com");
		new GooglePageRank(domain);
	}
}
